How to reverse a String in Java?
How to reverse a String in Java?
886
16-Nov-2021
Updated on 28-Apr-2023
Aryan Kumar
28-Apr-2023In Java, you can reverse a string by converting it into a StringBuilder object, then using the reverse() method to reverse the characters in the string. Here's an example code snippet that demonstrates how to reverse a string in Java:
In this example, we first create a string called originalString that we want to reverse. We then create a StringBuilder object and pass the original string as a parameter to the constructor.
Next, we call the reverse() method on the StringBuilder object to reverse the characters in the string. The reversed string is then stored in the reversedString variable.
Finally, we print out both the original string and the reversed string using the println() method.
Krishnapriya Rajeev
24-Mar-2023The code given below demonstrates how to reverse a string.
Mukul Goenka
16-Nov-2021import java.util.Scanner; public class HelloWorld { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println('Enter any string for reverse: '); String str = sc.nextLine(); System.out.println(reverse(str)); } public static String reverse(String in) { if (in == null) throw new IllegalArgumentException('Null is not valid input'); StringBuilder out = new StringBuilder(); char[] chars = in.toCharArray(); for (int i = chars.length - 1; i >= 0; i--) out.append(chars[i]); return out.toString(); } }Output.
Enter any string for reverse: Here are mindstick software pvt ltd.
.dtl tvp erawtfos kcitsdnim era ereH